Imports System.Windows.Forms
Imports System.ComponentModel
Imports System.Text
Imports FlickrNet
Imports System.IO
Imports System.Net
Imports System.Drawing

Public Class UploadPicture
  Private WithEvents _flickr As Flickr

  Private _Settings As Settings
  Private _UploadedPhotoID As UploadedPicture

  Private _UploadingPicture As Boolean

  Delegate Sub SetProgressValueDelegate(ByVal ByValValue As Integer)
  Delegate Sub SetStatusDelegate(ByVal Message As String)

#Region "Public"

  Public Property UploadedPicture() As UploadedPicture
    Get
      Return _UploadedPhotoID
    End Get
    Set(ByVal value As UploadedPicture)
      _UploadedPhotoID = value
    End Set
  End Property

  Public Overloads Function ShowDialog(ByVal parent As Object, ByVal pluginSettings As Settings) As DialogResult
    _Settings = pluginSettings
    Return Me.ShowDialog(parent)
  End Function


#End Region

#Region "Form events"
  Private Sub UploadPicture_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
    If _UploadingPicture Then
      MsgBox("Currently Uploading a Picture... When the upload is complete, this form will close by itself. Thank you", MsgBoxStyle.OkOnly, "Cannot Close While Uploading...")
      e.Cancel = True
      Return
    End If

    My.Settings.UploadPictureLocation = Me.Location
    My.Settings.UploadPictureDialogSize = Me.Size

    My.Settings.Save()

  End Sub

  Private Sub UploadPicture_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    If My.Settings.UploadPictureLocation.Height > -1 Then
      Me.Location = My.Settings.UploadPictureLocation
    End If

    If My.Settings.UploadPictureDialogSize.Height > -1 Then
      Me.Size = My.Settings.UploadPictureDialogSize
    End If

    If IO.Directory.Exists(Me._Settings.LastFolderUsed) Then
      Me.FilePicker1.InitialDirectory = Me._Settings.LastFolderUsed
    Else
      Me.FilePicker1.InitialDirectory = My.Computer.FileSystem.SpecialDirectories.MyPictures

    End If

    Select Case Me._Settings.CurrentPhotoService
      Case Settings.SupportedServiceList.Flickr
        Me.ServiceComboBox.SelectedIndex = 0
      Case Settings.SupportedServiceList.TwentyThreeHQ
        Me.ServiceComboBox.SelectedIndex = 1
      Case Else
        Me.ServiceComboBox.SelectedIndex = 0
    End Select

    Me.FilePicker1.DoSelectFile()
    If Me.FilePicker1.Filepath.Length = 0 Then
      Me.Close()
    End If

  End Sub

#End Region

#Region "Control events"
  Private Sub _flickr_OnUploadProgress(ByVal sender As Object, ByVal e As FlickrNet.UploadProgressEventArgs) Handles _flickr.OnUploadProgress

    If Not e.UploadComplete Then
      SetProgressValue(e.Bytes)
    Else
      SetStatus("Upload completed. Finishing up...")
      SetProgressValue(0)
    End If

  End Sub

  Private Sub Cancel_Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Cancel_Button.Click
    Me.DialogResult = System.Windows.Forms.DialogResult.Cancel
    Me.Close()
  End Sub

  Private Sub FilePicker1_FilePicked(ByVal sender As Object, ByVal e As System.EventArgs) Handles FilePicker1.FilePicked
    FileSelected()
  End Sub

  Private Sub FilePicker1_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles FilePicker1.TextChanged
    FileSelected()
  End Sub

  Private Sub ServiceComboBox_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ServiceComboBox.SelectedIndexChanged
    SetCurrentPhotoService()
  End Sub

  Private Sub UploadBackgroundWorker_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles UploadBackgroundWorker.DoWork
    SetStatus("Uploading picture")
    UploadPicture(Me.FilePicker1.Filepath, Me.TitleTextBox.Text, Me.DescriptionTextBox.Text, Me.TagsTextBox.Text)

  End Sub

  Private Sub UploadBackgroundWorker_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles UploadBackgroundWorker.RunWorkerCompleted
    EnableControls(True)

    SetStatus("")

    _UploadingPicture = False
    Me.DialogResult = System.Windows.Forms.DialogResult.OK
    Me.Close()

  End Sub

  Private Sub UploadButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles UploadButton.Click

    If Me.FilePicker1.Filepath.Length = 0 Then
      MsgBox("A file name is required. Please enter or select a file and try again.", MsgBoxStyle.OkOnly, "File Does Not Exist")
      Return
    End If

    If IO.File.Exists(Me.FilePicker1.Filepath) = False Then
      MsgBox(Me.FilePicker1.Filepath & " does not appear to exist. Please confirm the file exists and try again", MsgBoxStyle.OkOnly, "File Does Not Exist")
      Return
    End If

    _UploadingPicture = True

    Dim x As New IO.FileInfo(Me.FilePicker1.Filepath)
    Me.ToolStripProgressBar1.Maximum = x.Length
    x = Nothing


    EnableControls(False)

    SetCurrentPhotoService()

    UploadBackgroundWorker.RunWorkerAsync()

  End Sub


#End Region

#Region "Flickr Helpers"

  Private Function GetPhotoService() As Integer
    Select Case Me._Settings.CurrentPhotoService

      Case Settings.SupportedServiceList.Flickr
        Return FlickrNet.SupportedService.Flickr

      Case Settings.SupportedServiceList.TwentyThreeHQ
        Return FlickrNet.SupportedService.TwentyThreeHQ

      Case Else
        Return FlickrNet.SupportedService.Flickr

    End Select

  End Function

  Private Function GetServiceAuthToken() As String
    Dim frob As String

    Dim f As Flickr = New Flickr(My.Resources.FlickrAPIKey, My.Resources.FlickrSharedSecret)
    f.CurrentService = GetPhotoService()

    Dim wlwProxySettings As System.Net.WebProxy = WindowsLive.Writer.Api.PluginHttpRequest.GetWriterProxy()
    If wlwProxySettings IsNot Nothing Then
      f.Proxy = wlwProxySettings
    End If


    frob = f.AuthGetFrob()

    Dim url As String = f.AuthCalcUrl(frob, AuthLevel.Write)
    SetStatus("Requesting Authentication")

    Dim myProcess As Process = System.Diagnostics.Process.Start("Iexplore.exe", url)

    SetStatus("Waiting for Internet Explorer to be closed")
    myProcess.WaitForExit()

    SetStatus("Getting and saving authentication token")

    'TODO: Put in error handling
    Dim a As Auth = f.AuthGetToken(frob)

    Select Case Me._Settings.CurrentPhotoService
      Case Settings.SupportedServiceList.Flickr
        Me._Settings.FlickrAuthToken = a.Token

      Case Settings.SupportedServiceList.TwentyThreeHQ
        Me._Settings.TwentyThreeHQAuthToken = a.Token

      Case Else
        Me._Settings.FlickrAuthToken = a.Token

    End Select

    Return a.Token

  End Function

  Private Function IsAuthTokenValid(ByVal Token As String) As Boolean

    Dim f As Flickr = New Flickr(My.Resources.FlickrAPIKey, My.Resources.FlickrSharedSecret)
    f.CurrentService = GetPhotoService()

    Dim wlwProxySettings As System.Net.WebProxy = WindowsLive.Writer.Api.PluginHttpRequest.GetWriterProxy()
    If wlwProxySettings IsNot Nothing Then
      f.Proxy = wlwProxySettings
    End If


    Dim fAuth As Auth

    Try
      fAuth = f.AuthCheckToken(Token)

    Catch ex As FlickrException
      Return False

    End Try

    Return True

  End Function

  Private Sub SetCurrentPhotoService()
    Select Case Me.ServiceComboBox.SelectedIndex
      Case -1
        Me._Settings.CurrentPhotoService = Settings.SupportedServiceList.Flickr
      Case 0
        Me._Settings.CurrentPhotoService = Settings.SupportedServiceList.Flickr
      Case 1
        Me._Settings.CurrentPhotoService = Settings.SupportedServiceList.TwentyThreeHQ
      Case Else
        Me._Settings.CurrentPhotoService = Settings.SupportedServiceList.Flickr

    End Select

  End Sub

  Private Sub UploadPicture(ByVal FileName As String, ByVal Title As String, ByVal Description As String, ByVal Tags As String)
    Dim sServiceAuthToken As String

    Select Case Me._Settings.CurrentPhotoService
      Case Settings.SupportedServiceList.Flickr
        sServiceAuthToken = Me._Settings.FlickrAuthToken

      Case Settings.SupportedServiceList.TwentyThreeHQ
        sServiceAuthToken = Me._Settings.TwentyThreeHQAuthToken

      Case Else
        MsgBox("Unsupported photo service selected...")
        Return
    End Select

    If String.IsNullOrEmpty(sServiceAuthToken) Then
      sServiceAuthToken = GetServiceAuthToken()
    End If

    If String.IsNullOrEmpty(sServiceAuthToken) Then
      MsgBox("Unable to get your Authentication Token, so we're unable to upload. Don't know why this is happening at this point... Stupid Developer...")
      Return
    End If

    SetStatus("Checking Authentication Token")
    If IsAuthTokenValid(sServiceAuthToken) = False Then
      sServiceAuthToken = GetServiceAuthToken()
    End If

    'Dim _flickr As Flickr = New Flickr(My.Resources.FlickrAPIKey, My.Resources.FlickrSharedSecret, Me._Settings.FlickrAuthToken)
    _flickr = New Flickr(My.Resources.FlickrAPIKey, My.Resources.FlickrSharedSecret, sServiceAuthToken)
    _flickr.CurrentService = GetPhotoService()

    Dim wlwProxySettings As System.Net.WebProxy = WindowsLive.Writer.Api.PluginHttpRequest.GetWriterProxy()
    If wlwProxySettings IsNot Nothing Then
      _flickr.Proxy = wlwProxySettings
    End If


    If _flickr.IsAuthenticated = False Then
      sServiceAuthToken = GetServiceAuthToken()
    End If

    Dim uploadAsPublic As Boolean = False

    SetStatus("Uploading now...")

    Dim photoId As String = _flickr.UploadPicture(FileName, Title, Description, Tags, True, False, False)

    SetStatus("Uploaded as PhotoID " & photoId)
    _UploadedPhotoID = New UploadedPicture(photoId, FileName, Me._Settings.CurrentPhotoService)


  End Sub

#End Region

#Region "Helpers"

  Private Sub EnableControls(ByVal enable As Boolean)

    Me.Cancel_Button.Enabled = enable
    Me.UploadButton.Enabled = enable

    UploadingLabel.Visible = Not enable
    Me.TableLayoutPanel2.Enabled = enable

  End Sub

  Private Sub FileSelected()
    If IO.File.Exists(FilePicker1.Filepath) Then
      UploadButton.Enabled = True
      Me._Settings.LastFolderUsed = IO.Path.GetDirectoryName(FilePicker1.Filepath)
      Me.PictureBox1.ImageLocation = FilePicker1.Filepath
    End If

  End Sub

  Private Sub SetProgressValue(ByVal Value As Integer)

    If Me.InvokeRequired Then
      Dim myD1 As New SetProgressValueDelegate(AddressOf SetProgressValue)
      Me.Invoke(myD1, Value)
    Else
      If Value <= Me.ToolStripProgressBar1.Maximum Then
        Me.ToolStripProgressBar1.Value = Value
      Else
        Me.ToolStripProgressBar1.Value = Me.ToolStripProgressBar1.Maximum
      End If
    End If

  End Sub

  Private Sub SetStatus(ByVal Message As String)
    If Me.InvokeRequired Then
      Dim myD1 As New SetStatusDelegate(AddressOf SetStatus)
      Me.Invoke(myD1, Message)
    Else
      ToolStripStatusLabel1.Text = Message
    End If

  End Sub

#End Region

End Class
